package webapp;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import flca.mda.codegen.data.ITemplate;
import flca.mda.codegen.helpers.IPostProcess;
import flca.mda.codegen.helpers.SourceCodeUtils;

/**
 * this postprocess will remove import(s) that start with " java" from
 * flex-files and replace some known import(s) by the correct name.
 * 
 * @author nly36776
 * 
 */
public class ReplaceImportsPostprocessor implements IPostProcess{
	
	private static SourceCodeUtils su = new SourceCodeUtils();

	// TODO make more generic (using inifile ?)
	private static Map<String, String> sSubsKnownImports = new HashMap<String, String>();

	static {
		sSubsKnownImports.put("mda.annotation.jpa.", "javax.persistence.");
		sSubsKnownImports.put("mda.annotation.validation.", "org.hibernate.validator.");
	}

	@Override
	public String parse(String aInput, ITemplate aTemplate, Class<?> aTargetClass) {
		Collection<String> lines = su.getSourcecodeLines(aInput);
		return parseImportStatements(lines, isFlex(aTemplate));
	}
	
	@Override
	public boolean isApplicable(ITemplate aTemplate) {
		return true;
	}



	private String parseImportStatements(Collection<String> lines, boolean flex) {
		StringBuffer sb = new StringBuffer();
		for (String line : lines) {
			String parsedLine = line;
			if (su.isImportStatement(line)) {
				if (flex) {
					parsedLine = parseFlex(line);
				} else {
					parsedLine = parseJava(line);
				}
			}

			if (parsedLine != null) {
				sb.append(parsedLine + "\n");
			}
		}
		return sb.toString();
	}

	private String parseJava(String aImportLine) {
		String result = aImportLine;

		for (String subsfrom : sSubsKnownImports.keySet()) {
			String substo = sSubsKnownImports.get(subsfrom);
			result = result.replace(subsfrom, substo);
		}

		return result;
	}

	private String parseFlex(String aImportLine) {
		if (aImportLine.indexOf("java.") > 0) { // TODO
			return null;
		} else {
			return aImportLine;
		}
	}

	private boolean isFlex(ITemplate aTemplate) {
		return aTemplate.getName().startsWith("FLEX");
	}
	

}
